<?php

namespace App\Traits;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

trait SmsHelper
{
    use SignHelper;

    /**
     * 发送验证码
     * @param string $phone         手机号 字符串类型
     * @param int $templateType     短信模版ID
     * @param array $templateParam  短信模版映射参数 如：['username' => '张三']
     * @return bool                 发送成功或失败
     */
    public function sendSms(string $phone, int $templateType, array $templateParam = []) : bool
    {
        $config = config('common-api');
        $host = $config['host'] ?? '';
        $signName = $config['sms']['send']['signName'] ?? '';
        $uri = $config['sms']['send']['uri'] ?? '';

        if (empty($host) || empty($signName) || empty($uri)) {
            return false;
        }

        $params = [
            'phone' => $phone,
            'templateType' => $templateType,
            'signName' => $signName,
        ];
        if ($templateParam) {
            $params['templateParam'] = $templateParam;
        }
        $params['sign'] = $this->getSign($params);

        $httpClient = new Client();
        $uri = $host . $uri;
        try {
            $res = $httpClient->request('POST', $uri, ['json' => $params]);
            if ($res->getStatusCode() === 200) {
                $result = json_decode($res->getBody(), true);
                if ($result['status'] != 200) {
                    Log::error('短信验证码发送失败:', $result);
                    return false;
                }
            }
        } catch (GuzzleException $e) {
            Log::error($e->getMessage(), [$e->getCode(), $e->getTrace()]);
            return false;
        }

        return true;
    }

    /**
     * 验证短信验证码
     * @param string $phone             手机号 字符串类型
     * @param int $code                 验证码 需要验证的验证码
     * @param int $templateType         验证码所属的模版类型
     * @return array [bool, 'message']  ['验证结果', '结果信息']
     */
    public function verifySmsCode(string $phone, $code, int $templateType) : array
    {
        $config = config('common-api');
        $host = $config['host'] ?? '';
        $uri = $config['sms']['validate']['uri'] ?? '';

        if (empty($host) || empty($uri)) {
            return [false, 'config error'];
        }

        $params = [
            'phone' => $phone,
            'templateType' => $templateType,
            'code' => $code,
        ];

        $params['sign'] = $this->getSign($params);

        $httpClient = new Client();

        $uri = $host . $uri;
        try {
            $res = $httpClient->request('POST', $uri, ['json' => $params]);
            if ($res->getStatusCode() === 200) {
                $result = json_decode($res->getBody(), true);
                if ($result['status'] != 200) {
                    Log::error('短信码验证失败', $result);
                    return [false, '短信码验证失败'];
                }
            }
        } catch (GuzzleException $e) {
            Log::error($e->getMessage(), [$e->getCode(), $e->getTrace()]);
            return [false, 'system error'];
        }

        return [true, 'success'];
    }
}
